<?php
/**
 * 支付接口调测例子
 * ================================================================
 * index 进入口，方法中转
 * submitOrderInfo 提交订单信息
 * queryOrder 查询订单
 * 
 * ================================================================
 */
require('Utils.class.php');
//require('config/config.php');
require('class/RequestHandler.class.php');
require('class/ClientResponseHandler.class.php');
require('class/PayHttpClient.class.php');

Class Request{
    //$url = 'http://192.168.1.185:9000/pay/gateway';

    private $resHandler = null;
    private $reqHandler = null;
    private $pay = null;
    private $mch_id = null;
    private $body = null;
    //private $cfg = null;
    
    public function __construct($private_rsa_key='',$public_rsa_key='',$mch_id='',$body=''){
    	$this->mch_id = $mch_id;
    	$this->body = $body;
    	$this->resHandler = new ClientResponseHandler();
        $this->reqHandler = new RequestHandler();
        $this->pay = new PayHttpClient();
        $this->reqHandler->setGateUrl('https://pay.spdb.swiftpass.cn/pay/gateway');
        $this->reqHandler->setRSAKey($private_rsa_key);
        $this->resHandler->setRSAKey($public_rsa_key);
        $this->reqHandler->setSignType('RSA_1_256');
        //$this->Request();
    }

    public function Request(){
        $this->resHandler = new ClientResponseHandler();
        $this->reqHandler = new RequestHandler();
        $this->pay = new PayHttpClient();
        $this->cfg = new Config();

        $this->reqHandler->setGateUrl($this->cfg->C('url'));
        $sign_type = $this->cfg->C('sign_type');
     		   
        if ($sign_type == 'MD5') {
            $this->reqHandler->setKey($this->cfg->C('key'));
            $this->resHandler->setKey($this->cfg->C('key'));
            $this->reqHandler->setSignType($sign_type);
        } else if ($sign_type == 'RSA_1_1' || $sign_type == 'RSA_1_256') {
            $this->reqHandler->setRSAKey($this->cfg->C('private_rsa_key'));
            $this->resHandler->setRSAKey($this->cfg->C('public_rsa_key'));
            $this->reqHandler->setSignType($sign_type);
        }
    }
    
    public function index(){
        /*$method = isset($_REQUEST['method'])?$_REQUEST['method']:'submitOrderInfo';
        switch($method){
            case 'submitOrderInfo'://提交订单
                $this->submitOrderInfo();
            break;
            case 'queryOrder'://查询订单
                $this->queryOrder();
            break;
            case 'submitRefund'://提交退款
                $this->submitRefund();
            break;
            case 'queryRefund'://查询退款
                $this->queryRefund();
            break;
			case 'closeOrder'://关闭订单
                $this->closeOrder();
            break;
            case 'callback':
                $this->callback();
            break;
        }*/
    }
    
    /**
     * 提交订单信息
     */
    public function submitOrderInfo($orderdata){
		$cip = "unknown";
		if($_SERVER['REMOTE_ADDR']){
			$cip = $_SERVER['REMOTE_ADDR'];
		}else if(getenv("REMOTE_ADDR")){
			$cip = getenv(['REMOTE_ADDR']);
		}

		$this->reqHandler->setParameter('out_trade_no',$orderdata['out_trade_no']);	
		$this->reqHandler->setParameter('total_fee',$orderdata['total_fee']);
		$this->reqHandler->setParameter('mch_create_ip',$cip);
		$this->reqHandler->setParameter('body',$this->body);
        $this->reqHandler->setParameter('service','pay.weixin.jspay');//接口类型：pay.weixin.jspay
        $this->reqHandler->setParameter('mch_id',$this->mch_id);//必填项，商户号，由平台分配
        $this->reqHandler->setParameter('version','2.0');
        $this->reqHandler->setParameter('sign_type','RSA_1_256');
		$this->reqHandler->setParameter('notify_url',$orderdata['notify_url']);//支付成功异步回调通知地址，目前默认是空格，商户在测试支付和上线时必须改为自己的，且保证外网能访问到
		// $this->reqHandler->setParameter('callback_url','http://www.swiftpass.com');
		$this->reqHandler->setParameter('sub_appid',$orderdata['sub_appid']);//对应公众号appid，使用测试号时置空，使用正式商户号时必填
		$this->reqHandler->setParameter('sub_openid',$orderdata['sub_openid']);//对应公众号获取到的用户openid，使用测试号时置空，使用正式商户号时必填(使用微信官方网页授权接口获取地址：            https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842&token=&lang=zh_CN )
        $this->reqHandler->setParameter('is_raw','1');
        if($orderdata['is_minipg']){
        	$this->reqHandler->setParameter('is_minipg','1');
        }
        $this->reqHandler->setParameter('nonce_str',mt_rand());//随机字符串，必填项，不长于 32 位
        $this->reqHandler->createSign();//创建签名
        
        $data = Utils::toXml($this->reqHandler->getAllParameters());
		
        Utils::dataRecodes(date("Y-m-d H:i:s",time()).'公众号支付请求XML',$data);//请求xml记录到result.txt
        $this->pay->setReqContent($this->reqHandler->getGateURL(),$data);
		
        if($this->pay->call()){
            $this->resHandler->setContent($this->pay->getResContent());
            $this->resHandler->setKey($this->reqHandler->getKey());
            $res = $this->resHandler->getAllParameters();
            Utils::dataRecodes(date("Y-m-d H:i:s",time()).'支付返回XML',$res);
            if($this->resHandler->isTenpaySign()){
                
                if($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0){
                    //当返回状态与业务结果都为0时继续判断
                    //echo json_encode(array('status'=>200,'data'=>$res));
					return json_decode($this->resHandler->getParameter('pay_info'),true);exit;
                    /*echo json_encode(array('code_img_url'=>$this->resHandler->getParameter('code_img_url'),
                                        'pay_info'=>$this->resHandler->getParameter('pay_info')));
                    exit();*/
                }else{
                    return $this->resHandler->getParameter('message').$this->resHandler->getParameter('err_code').$this->resHandler->getParameter('err_msg');
                    exit();
                }
            }
            return $this->resHandler->getParameter('message');
        }else{
            return 'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo();
        }
    }

    /**
     * 查询订单
     */
    public function queryOrder(){
        $this->reqHandler->setReqParams($_POST,array('method'));
        $reqParam = $this->reqHandler->getAllParameters();
        if(empty($reqParam['transaction_id']) && empty($reqParam['out_trade_no'])){
            echo json_encode(array('status'=>500,
                                   'msg'=>'请输入商户订单号,平台订单号!'));
            exit();
        }
        $this->reqHandler->setParameter('version',$this->cfg->C('version'));
        $this->reqHandler->setParameter('service','unified.trade.query');//接口类型：unified.trade.query
        $this->reqHandler->setParameter('mch_id',$this->cfg->C('mchId'));//必填项，商户号，由平台分配
        $this->reqHandler->setParameter('sign_type',$this->cfg->C('sign_type'));
        $this->reqHandler->setParameter('nonce_str',mt_rand());//随机字符串，必填项，不长于 32 位
        $this->reqHandler->createSign();//创建签名
        $data = Utils::toXml($this->reqHandler->getAllParameters());

        Utils::dataRecodes(date("Y-m-d H:i:s",time()).'查询请求XML',$data);//请求xml记录到result.txt
        $this->pay->setReqContent($this->reqHandler->getGateURL(),$data);
        if($this->pay->call()){
            $this->resHandler->setContent($this->pay->getResContent());
            $this->resHandler->setKey($this->reqHandler->getKey());
			$res = $this->resHandler->getAllParameters();
			Utils::dataRecodes(date("Y-m-d H:i:s",time()).'查询返回XML',$res);
            if($this->resHandler->isTenpaySign()){           
                if($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0){
					
					echo json_encode(array('status'=>200,'msg'=>'订单状态：'.$this->resHandler->getParameter('trade_state')));
                    exit();
                }else{
                    echo json_encode(array('status'=>500,'msg'=>$this->resHandler->getParameter('message').$this->resHandler->getParameter('err_code').$this->resHandler->getParameter('err_msg')));
                    exit();
                }
            }
            echo json_encode(array('status'=>500,'msg'=>$this->resHandler->getParameter('message')));
        }else{
            echo json_encode(array('status'=>500,'msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo()));
        }
    }
    
	
	 /**
     * 提交退款
     */
    public function submitRefund($transaction_id,$out_trade_no,$total_fee,$refund_fee){
    	$this->reqHandler->setParameter('transaction_id',$transaction_id);
    	$this->reqHandler->setParameter('out_refund_no',$out_trade_no);
    	$this->reqHandler->setParameter('total_fee',$total_fee*100);
    	$this->reqHandler->setParameter('refund_fee',$refund_fee*100);
        /*$this->reqHandler->setReqParams($_POST,array('method'));
        $reqParam = $this->reqHandler->getAllParameters();
        if(empty($reqParam['transaction_id']) && empty($reqParam['out_trade_no'])){
            echo json_encode(array('status'=>500,
                                   'msg'=>'请输入商户订单号或平台订单号!'));
            exit();
        }*/
        $this->reqHandler->setParameter('version','2.0');
        $this->reqHandler->setParameter('service','unified.trade.refund');//接口类型：unified.trade.refund
        $this->reqHandler->setParameter('mch_id',$this->mch_id);//必填项，商户号，由平台分配
        $this->reqHandler->setParameter('nonce_str',mt_rand());//随机字符串，必填项，不长于 32 位
        $this->reqHandler->setParameter('sign_type','RSA_1_256');
        $this->reqHandler->setParameter('op_user_id',$this->mch_id);//必填项，操作员帐号,默认为商户号

        $this->reqHandler->createSign();//创建签名
         $data = Utils::toXml($this->reqHandler->getAllParameters());//将提交参数转为xml，目前接口参数也只支持XML方式
		Utils::dataRecodes(date("Y-m-d H:i:s",time()).'退款申请请求XML',$data);//请求xml记录到result.txt
        $this->pay->setReqContent($this->reqHandler->getGateURL(),$data);
        if($this->pay->call()){
            $this->resHandler->setContent($this->pay->getResContent());
            $this->resHandler->setKey($this->reqHandler->getKey());
			$res = $this->resHandler->getAllParameters();
			Utils::dataRecodes(date("Y-m-d H:i:s",time()).'退款申请返回XML',$res);
            if($this->resHandler->isTenpaySign()){
                if($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0){
                	$result = array(
						'return_code'=>'SUCCESS',
						'result_code'=>'SUCCESS'
					);
					return $result;exit;
					//echo json_encode(array('status'=>200,'msg'=>'退款申请成功，请查看result.txt文件！'));
                    //exit();
                }else{
                	$result = array(
						'return_msg'=>$this->resHandler->getParameter('message').$this->resHandler->getParameter('err_code').$this->resHandler->getParameter('err_msg')
					);
					return $result;exit;
                    //echo json_encode(array('status'=>500,'msg'=>$this->resHandler->getParameter('message').$this->resHandler->getParameter('err_code').$this->resHandler->getParameter('err_msg')));
                    //exit();
                }
            }
            $result = array(
				'return_msg'=>$this->resHandler->getParameter('message')
			);
			return $result;exit;
            //echo json_encode(array('status'=>500,'msg'=>$this->resHandler->getParameter('message')));
        }else{
            $result = array(
				'return_msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo()
			);
			return $result;exit;
            //echo json_encode(array('status'=>500,'msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo()));
        }
    }

    /**
     * 查询退款
     */
    public function queryRefund(){
        $this->reqHandler->setReqParams($_POST,array('method'));
        if(count($this->reqHandler->getAllParameters()) === 0){
            echo json_encode(array('status'=>500,
                                   'msg'=>'请输入商户订单号,平台订单号,商户退款单号,平台退款单号!'));
            exit();
        }
        $this->reqHandler->setParameter('version',$this->cfg->C('version'));
        $this->reqHandler->setParameter('service','unified.trade.refundquery');//接口类型：unified.trade.refundquery
        $this->reqHandler->setParameter('mch_id',$this->cfg->C('mchId'));//必填项，商户号，由平台分配
        $this->reqHandler->setParameter('sign_type',$this->cfg->C('sign_type'));
        $this->reqHandler->setParameter('nonce_str',mt_rand());//随机字符串，必填项，不长于 32 位
        
        $this->reqHandler->createSign();//创建签名
        $data = Utils::toXml($this->reqHandler->getAllParameters());//将提交参数转为xml，目前接口参数也只支持XML方式

        Utils::dataRecodes(date("Y-m-d H:i:s",time()).'退款查询请求XML',$data);//请求xml记录到result.txt
        $this->pay->setReqContent($this->reqHandler->getGateURL(),$data);
        if($this->pay->call()){
            $this->resHandler->setContent($this->pay->getResContent());
            $this->resHandler->setKey($this->reqHandler->getKey());
			$res = $this->resHandler->getAllParameters();
			Utils::dataRecodes(date("Y-m-d H:i:s",time()).'退款查询返回XML',$res);
            if($this->resHandler->isTenpaySign()){
                if($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0){
					echo json_encode(array('status'=>200,'msg'=>'结果请查看result.txt文件！'));
                    exit();
                }else{
                    echo json_encode(array('status'=>500,'msg'=>$this->resHandler->getParameter('message').$this->resHandler->getParameter('err_code').$this->resHandler->getParameter('err_msg')));
                    exit();
                }
            }
            echo json_encode(array('status'=>500,'msg'=>$this->resHandler->getParameter('message')));
        }else{
            echo json_encode(array('status'=>500,'msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo()));
        }
    }
    /**
     * 关闭订单
     */
    public function closeOrder(){
        $this->reqHandler->setReqParams($_POST,array('method'));
		$reqParam = $this->reqHandler->getAllParameters();
        if(empty($reqParam['out_trade_no'])){
            echo json_encode(array('status'=>500,
                                   'msg'=>'请输入商户订单号!'));
            exit();
        }
        $this->reqHandler->setParameter('version',$this->cfg->C('version'));
        $this->reqHandler->setParameter('service','unified.trade.close');//接口类型：unified.trade.close
        $this->reqHandler->setParameter('mch_id',$this->cfg->C('mchId'));//必填项，商户号，由平台分配
        $this->reqHandler->setParameter('sign_type',$this->cfg->C('sign_type'));
        $this->reqHandler->setParameter('nonce_str',mt_rand());//随机字符串，必填项，不长于 32 位
        
        $this->reqHandler->createSign();//创建签名
        $data = Utils::toXml($this->reqHandler->getAllParameters());//将提交参数转为xml，目前接口参数也只支持XML方式

        Utils::dataRecodes(date("Y-m-d H:i:s",time()).'关闭订单请求XML',$data);//请求xml记录到result.txt
        $this->pay->setReqContent($this->reqHandler->getGateURL(),$data);
        if($this->pay->call()){
            $this->resHandler->setContent($this->pay->getResContent());
            $this->resHandler->setKey($this->reqHandler->getKey());
			$res = $this->resHandler->getAllParameters();
			Utils::dataRecodes(date("Y-m-d H:i:s",time()).'关闭订单返回XML',$res);
            if($this->resHandler->isTenpaySign()){
                if($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0){
					echo json_encode(array('status'=>200,'msg'=>'结果请查看result.txt文件！'));
                    exit();
                }else{
                    echo json_encode(array('status'=>500,'msg'=>$this->resHandler->getParameter('message').$this->resHandler->getParameter('err_code').$this->resHandler->getParameter('err_msg')));
                    exit();
                }
            }
            echo json_encode(array('status'=>500,'msg'=>$this->resHandler->getParameter('message')));
        }else{
            echo json_encode(array('status'=>500,'msg'=>'Response Code:'.$this->pay->getResponseCode().' Error Info:'.$this->pay->getErrInfo()));
        }
    }
    /**
     * 异步通知回调
     */
    public function callback(){
        $xml = file_get_contents('php://input');
		file_put_contents('1.txt',$xml);//检测是否执行callback方法，如果执行，会生成1.txt文件，且文件中的内容就是通知参数
        $this->resHandler->setContent($xml);
		//var_dump($this->resHandler->setContent($xml));
        //$this->resHandler->setKey($this->cfg->C('key'));
        if($this->resHandler->isTenpaySign()){
            if($this->resHandler->getParameter('status') == 0 && $this->resHandler->getParameter('result_code') == 0){
				// 此处可以在添加相关处理业务，校验通知参数中的商户订单号out_trade_no和金额total_fee是否和商户业务系统的单号和金额是否一致，一致后方可更新数据库表中的记录。
				//更改订单状态
				$result = array(
					'out_trade_no'=>$this->resHandler->getParameter('out_trade_no'),
					'transaction_id'=>$this->resHandler->getParameter('transaction_id'),
					'total_fee'=>$this->resHandler->getParameter('total_fee'),
					'return_code'=>'SUCCESS',
					'result_code'=>'SUCCESS'
				);
				file_put_contents('2.txt',json_encode($result));
				return $result;exit;
                Utils::dataRecodes('接口回调收到通知参数',$this->resHandler->getAllParameters());
				ob_clean();
                echo 'success';
				file_put_contents('2.txt',1);//如果生成2.txt,说明前一步的输出success是有执行
                exit();
            }else{
                echo 'failure1';
                exit();
            }
        }else{
            echo 'failure2';
        }
    }
}

$req = new Request();
$req->index();
?>